package com.vgmobile.cucrever2.home;

import java.util.ArrayList;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.special.ResideMenu.ResideMenu;
import com.vgmobile.cucrever2.R;
import com.vgmobile.cucrever2.ResideMenuActivity;
import com.vgmobile.cucrever2.api.ItemListHoz;
import com.vgmobile.cucrever2.constant.KeyFragment;
import com.vgmobile.cucrever2.home.category.CategoryParentFragment;
import com.vgmobile.cucrever2.product.detail.ProductDetailActivity;
import com.vgmobile.cucrever2.product.list.ProductListActivity;
import com.viewpagerindicator.CirclePageIndicator;

public class HomeFragment extends Fragment {

	private final int ACTION_NEXT_EVENT = 1;

	private ResideMenuActivity activity;
	private ResideMenu resideMenu;
	private Handler mHandler;
	private View view = null;

	private LinearLayout linearLayout;
	private RelativeLayout btnShopping;

	ArrayList<ItemListHoz> listSuggestProduct;
	private ListHorizontalView suggestProductListView;
	private ListHorizontalAdapter listHorizontalAdapter;

	// Advertise
	private AdvGridExpandableView advGridView;
	private AdvGridExpandableAdapter advGridExpandableAdapter;
	ArrayList<ItemAdvertise> listItemAdv;

	// Event
	private EventAdapter eventAdapter;
	private ViewPager eventViewPager;
	ArrayList<ItemEvent> listItemEvent;
	private CirclePageIndicator homeEventIndicator;
	private boolean isRunning;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if (view == null) {
			mHandler = new Handler() {
				public void handleMessage(android.os.Message msg) {
					switch (msg.what) {
					case ACTION_NEXT_EVENT:
						if (eventAdapter.getCount()>0) {
							int pos = (eventViewPager.getCurrentItem() + 1)
									% eventAdapter.getCount();
							eventViewPager.setCurrentItem(pos);
						}
						
						break;
					}
				};
			};
			view = inflater.inflate(R.layout.home_fragment_layout, container,
					false);
			linearLayout = (LinearLayout) view
					.findViewById(R.id.store_parentlayout);
			btnShopping = (RelativeLayout) view
					.findViewById(R.id.store_btn_shopping);
			suggestProductListView = (ListHorizontalView) view
					.findViewById(R.id.store_listhozview);
			advGridView = (AdvGridExpandableView) view
					.findViewById(R.id.store_gridview);
			eventViewPager = (ViewPager) view
					.findViewById(R.id.store_event_viewpager);

			activity = (ResideMenuActivity) getActivity();
			resideMenu = activity.getResideMenu();

			advGridView.setExpanded(true);

			eventViewPager.setOffscreenPageLimit(0);
		} else {
			((ViewGroup) view.getParent()).removeView(view);
		}

		listSuggestProduct = new ArrayList<ItemListHoz>();
		listHorizontalAdapter = new ListHorizontalAdapter(activity, listSuggestProduct);
		suggestProductListView.setAdapter(listHorizontalAdapter);
		
		listItemAdv = new ArrayList<ItemAdvertise>();
		advGridExpandableAdapter = new AdvGridExpandableAdapter(activity,
				listItemAdv);
		advGridView.setAdapter(advGridExpandableAdapter);

		listItemEvent = new ArrayList<ItemEvent>();
		eventAdapter = new EventAdapter(activity, listItemEvent);
		eventViewPager.setAdapter(eventAdapter);
		
		homeEventIndicator = (CirclePageIndicator) view
				.findViewById(R.id.store_event_indicator);
		homeEventIndicator.setFillColor(getResources().getColor(
				R.color.circle_indicator_fill_color));
		homeEventIndicator.setPageColor(getResources().getColor(
				R.color.circle_indicator_page_color));
		homeEventIndicator.setStrokeWidth(0);
		homeEventIndicator.setViewPager(eventViewPager);
		homeEventIndicator.setCurrentItem(0);
        startUpdateEventPage();
        
		activity.setTitleMenuHome(null);
		activity.setOnBackPressedListener(null);
		isRunning = true;
		
		loadEvents();
		loadAdvertise();
		loadSuggestProducts();
		
		return view;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		btnShopping.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				Fragment newFragment = new CategoryParentFragment();
				activity.nextFragment(newFragment,
						ResideMenuActivity.TAG_FRAGMENT_HOME);
			}
		});

		advGridView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> adapterView, View view,
					int postion, long id) {
				Bundle params = new Bundle();
				ItemAdvertise itemAdv = (ItemAdvertise) listItemAdv.get(postion);
				params.putString(KeyFragment.KEY_CATE_ID, itemAdv.getAdvId());
				params.putString(KeyFragment.KEY_CATE_NAME, itemAdv.getAdvName());
				params.putString(KeyFragment.KEY_CATE_IMG_LINK, itemAdv.getImageLink());
				Intent intent = new Intent(activity, ProductListActivity.class);
				intent.putExtras(params);
				activity.startActivity(intent);
			    activity.overridePendingTransition(R.anim.activity_fade_in, R.anim.activity_fade_out);
			}

		});
		eventViewPager.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				int position = eventViewPager.getCurrentItem();
				Bundle params = new Bundle();
				ItemEvent itemEvent = (ItemEvent) listItemEvent.get(position);
				params.putString(KeyFragment.KEY_CATE_ID, itemEvent.getEventId());
				params.putString(KeyFragment.KEY_CATE_NAME, itemEvent.getEventName());
				params.putString(KeyFragment.KEY_CATE_IMG_LINK, itemEvent.getImageLink());
				Intent intent = new Intent(activity, ProductListActivity.class);
				intent.putExtras(params);
				activity.startActivity(intent);
			    activity.overridePendingTransition(R.anim.activity_fade_in, R.anim.activity_fade_out);
			}
		});
		suggestProductListView
				.setOnItemClickListener(new OnItemClickListener() {
					public void onItemClick(AdapterView<?> adapterView,
							View view, int postion, long id) {
						Intent intent = new Intent(activity,
								ProductDetailActivity.class);
						activity.startActivity(intent);
						activity.overridePendingTransition(
								R.anim.activity_fade_in,
								R.anim.activity_fade_out);
					}
				});

	}

	@Override
	public void onDestroyView() {
		// gridExpandableAdapter.clearMem();
		// listHorizontalAdapter.clearMem();
		// unbindDrawables(listView);
		// unbindDrawables(gridView);
		// unbindDrawables(linearLayout);
		System.gc();
		isRunning = false;
		Log.d("AAA", "onDestroyView  StoreFragment");
		super.onDestroyView();
	}

	public boolean isRunning() {
		return isRunning;
	}

	private void unbindDrawables(View view) {
		try {
			if (view.getBackground() != null) {
				view.getBackground().setCallback(null);
			}
			if (view instanceof ViewGroup) {
				for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
					unbindDrawables(((ViewGroup) view).getChildAt(i));
				}
				try {
					((ViewGroup) view).removeAllViews();
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	
	/**
	 * Vòng lặp cập nhật trang sự kiện (banner top) sau mỗi 5s
	 */
	public void startUpdateEventPage() {
		

		Thread t = new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					Thread.sleep(5 * 1000);
				} catch (InterruptedException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				while (isRunning) {
					try {
						Message msg = new Message();
						msg.what = ACTION_NEXT_EVENT;
						mHandler.sendMessage(msg);
						Thread.sleep(5 * 1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		});
		t.start();
	}

	/**
	 * Tải dữ liệu quảng cáo (4 item quare)
	 */
	public void loadAdvertise() {
		listItemAdv = new ArrayList<ItemAdvertise>();
		for (int i = 0; i < 4; i++) {
			String id = "" + i;
			String name = "Event " + i;
			String imgLink = "https://dl.dropboxusercontent.com/u/71228229/TestCucre/"
					+ i + ".jpg";
			ItemAdvertise item = new ItemAdvertise(id, name, imgLink);
			listItemAdv.add(item);
		}

		advGridExpandableAdapter = new AdvGridExpandableAdapter(activity,
				listItemAdv);
		advGridView.setAdapter(advGridExpandableAdapter);
		advGridExpandableAdapter.notifyDataSetChanged();
	}

	/**
	 * Tải dữ liệu sự kiện (banner top)
	 */
	public void loadEvents() {
		listItemEvent = new ArrayList<ItemEvent>();
		for (int i = 0; i < 5; i++) {
			ItemEvent item = new ItemEvent();
			if (i % 2 == 0) {
				item.setImageLink("https://dl.dropboxusercontent.com/u/71228229/TestCucre/event_1.png");
			} else {
				item.setImageLink("https://dl.dropboxusercontent.com/u/71228229/TestCucre/event_2.png");
			}
			item.setEventName("World Class " + i);
			listItemEvent.add(item);
		}
		listItemEvent = new ArrayList<ItemEvent>();
		eventAdapter = new EventAdapter(activity, listItemEvent);
		eventViewPager.setAdapter(eventAdapter);
	}
	
	
	/**
	 * Tải dữ liệu các sản phẩm gợi ý (Có thể bạn sẽ thích)
	 */
	public void loadSuggestProducts()
	{
		listSuggestProduct = new ArrayList<ItemListHoz>();
		for (int i = 0; i < 12; i++) {
			ItemListHoz itemListHoz = new ItemListHoz();
			itemListHoz
					.setLinkImage("https://dl.dropboxusercontent.com/u/71228229/TestCucre/4.jpg");
			itemListHoz.setTitle("Sạc pin dự phòng K180-12R 7800mAh");
			itemListHoz.setPrice("600.000đ");
			listSuggestProduct.add(itemListHoz);
		}
		listHorizontalAdapter = new ListHorizontalAdapter(activity, listSuggestProduct);
		suggestProductListView.setAdapter(listHorizontalAdapter);
		listHorizontalAdapter.notifyDataSetChanged();
	}
}
